<?php
define( "SELECT", "select" );
define( "UPDATE", "update" );
define( "TEST",   "test"   );

$stmt = create_statement();
bind_params( $stmt );
$uid         = get_request( "username",     1 );
$pass        = get_request( "password",     1 );
$action      = get_request( "action",       SELECT );
$mark_id     = get_request( "bookmark_id",   'A');
$site        = get_request( "site",       'http://googlesystem.blogspot.com/2009/09/embeddable-google-document-viewer.html');
$stmt->execute();
echo_results( $stmt->fetch( PDO::FETCH_ASSOC ), $stmt->errorInfo() );

function create_statement()
{
    $pdo       = create_pdo();
    $stmt = $pdo->prepare( get_action() );
    if( $stmt === FALSE )  die( print_r( $pdo->errorInfo() ) );
    else return $stmt;
}

function create_pdo()
{
    $config     = parse_ini_file( dirname( __FILE__ ) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'ini/dbsettings.ini' );
    return new PDO( "{$config[ 'dbtype' ]}:dbname={$config[ 'dbname' ]};host={$config[ 'host' ]};", $config[ 'user' ], $config[ 'password' ] );
}

// I realize that this is a very long function, but all it is really doing is, "Get this information, set it there, get this other piece of information, set it there..."
function bind_params( PDOStatement $stmt )
{
    $action      = get_request( "action", SELECT );
    bind_credentials( $stmt );
    if( $action == TEST )
    {
        $stmt->execute();
        $res = $stmt->fetchAll()? TRUE: FALSE;
        echo_results( array( "isKeepOrielServer" => TRUE, "loginSuccessful" => $res ), FALSE );
        die();
    }
    else
    {
        bind_generic_params( $stmt );
        if( $action == UPDATE ) 
        {
            bind_update_params( $stmt );
        }
    }
}

function bind_credentials( PDOStatement $stmt )
{
    $uid         = get_request( "username",     1 );
    $pass        = get_request( "password",     1 );
    $stmt->bindParam( ":uid",     $uid,         PDO::PARAM_STR ); 
    $stmt->bindParam( ":pass",     $pass,         PDO::PARAM_STR );
}

function bind_generic_params( PDOStatement $stmt )
{
    // defaults are all test data
    $mark_id     = get_request( "bookmark_id",   'A');
    $site        = get_request( "site",       'http://googlesystem.blogspot.com/2009/09/embeddable-google-document-viewer.html');
    $stmt->bindParam( ":mark_id",     $mark_id,     PDO::PARAM_STR );
    $stmt->bindParam( ":site",        $site,         PDO::PARAM_STR );
}

function bind_update_params( PDOStatement $stmt )
{
   // default to NaN to prevent accidental misset.
    $pos = get_request( "position", 'A' ) + 0;
    $stmt->bindParam( ":pos",         $pos,     PDO::PARAM_INT );
    $height = get_request( "height", 0 ) + 0;
    $stmt->bindParam( ":height",         $height,     PDO::PARAM_INT );

    $width = get_request( "width", 0 ) + 0;
    $stmt->bindParam(   ":width",         $width,     PDO::PARAM_INT );
    $root_hash = get_request( "root_hash", 0 );
    $stmt->bindParam(   ":root_hash",     $root_hash,         PDO::PARAM_STR );
}

function get_action()
{
    $dbAction    = get_request( "action", SELECT );
    $config     = parse_ini_file( dirname( __FILE__ ) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '/ini/dbsettings.ini' ); // Will be removed later.

    if( $dbAction == TEST )
    {
        $dbAction = $config[ 'mysql_get_id' ];
    }
    elseif( $dbAction != UPDATE )
    {
        $dbAction = "SELECT position AS scroll_top, height, width, site_root_hash as root_hash, site FROM {$config[ 'dbtable' ]} WHERE USER_ID = {$config[ 'mysql_get_id' ]} AND MARK_NAME=:mark_id AND SITE=:site";
    }
    else
    {
        // There is a DB rule which handles duplicate records.  This means that the action can 
        // treat everything as if it were an insert and thus minimize the connections to the DB
        // "INSERT INTO $dbTable ( site, position, user_id, mark_name, height, width, site_root_hash ) VALUES ( :site, :pos, $idQuery, :mark_id, :height, :width, :root_hash )";
        $dbAction = sprintf( $config[ 'mysql_insert' ], $config[ 'dbtable' ], $config[ 'mysql_get_id' ] );
    }
    return $dbAction;
}

function echo_results( $res, $code )
{
    // If there is no error code, set code to be something other than an array
    if( is_array( $code ) && $code[ 0 ] = "00000" ) $code = false;
    // Otherwise, if res is a boolean (ie. false), then use the error array as the sent array.
    elseif( !is_array( $res ) && is_array( $code ) )
    {
        $res = $code;
        // Data we'd rather not have the user see.
        unset( $res[ 0 ] );
        unset( $res[ 2 ] );
        $res[ "cause" ] = $res[ 1 ];
    }
    // Data sanitation.  We can have $res be a Boolean, but no error code, then we have no array
    if( !is_array( $res ) ) $res = array();
    $res[ "success" ] = ( is_array( $code) )? false:true;
    $gt = $_GET;
    foreach( $gt as $key=>$value ){ unset( $gt[ $key ] ); $gt[ "_$key" ] = $value;}
    echo json_encode( array_merge( $res, $gt));// _GET ) );
}

function get_request( $key, $default = null )
{
    if( isset( $_REQUEST[ $key ] ) )
    {
        return $_REQUEST[ $key ];
    }
    echo "<br />$key";
    if( is_null( $default ) ) return $key;
    return $default;
}
